const express = require("express");
const chinas = require("../../public/code.json");
const china = chinas.map((r, i) => {
  return {
    pid: r.pid,
    name: r.name,
    nubs: ++i,
    children: r.children,
    // 停电线路
    deadLine: {
      total: 5,
      numbers: 1,
    },
    // 整线停电
    allPowerCut: {
      total: 5,
      numbers: 4,
    },
    // 支线停电
    branchPowerCut: {
      total: 0,
      numbers: 0,
    },
    // 配变停电
    distributionPowerCut: {
      total: 50,
      numbers: 10,
    },
    // 单配变停电
    branchDistributionPowerCut: {
      total: 0,
      numbers: 0,
    },
    // 停电用户
    powerCutUser: {
      total: 500,
      numbers: 200,
    },
  };
});

const Line = [
  {
    id: 1,
    name: "线路",
    children: [
      {
        id: 1001,
        name: "北京",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "南京",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "上海",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "北京",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "南京",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "上海",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
    ],
  },
  {
    id: 2,
    name: "配变",
    children: [
      {
        id: 1001,
        name: "江苏",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "北京",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "天津",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "江苏",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "北京",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "天津",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
    ],
  },
  {
    id: 3,
    name: "用户",
    children: [
      {
        id: 1001,
        name: "福建",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "湖南",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "广东",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "福建",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "湖南",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
      {
        id: 1001,
        name: "广东",
        children: [
          {
            zx: 200,
            zxwhf: 40,
            zhixian: 180,
            zxhixianwhf: 60,
          },
        ],
      },
    ],
  },
];

// 用户信息
const users = [
  {
    Useranme: "admin",
    login: "admin",
    Password: "123456",
    ConfirmPassword: "123456",
    headPortrait:
      "https://img1.baidu.com/it/u=3178057158,4110048229&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1668877200&t=744fdc082400ce0006aebca8fe069145",
  },
];


// 轮盘数据
const  imgList= [
  {
    no: 1,
    title: "随机矿石",
    imgs: "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/32ed6a7619934144882d841761b63d3c~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp",
  },
  {
    no: 2,
    title: "Bug",
    imgs: "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0a4ce25d48b8405cbf5444b6195928d4~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp",
  },
  {
    no: 3,
    title: "稀土掘金口罩",
    imgs: "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bcad989d25ab4377b0656877721406d7~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp?",
  },
  {
    no: 4,
    title: "解压工卡套",
    imgs: "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7c606de3f5994b9bbb39bab1ab6927bb~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp?",
  },
  {
    no: 5,
    title: "曼秀雷敦唇膏",
    imgs: "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a8a65cb2605c493faa24351c8c4590ef~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp?",
  },
  {
    no: 6,
    title: "Hawking拍拍灯",
    imgs: "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7cb401321ffd434eb63e2c578a09c412~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp?",
  },
  {
    no: 7,
    title: "稀土掘金兔年春节礼盒",
    imgs: "https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d748a2d93d6840da84e9f9c2ac347241~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp?",
  },
  {
    no: 8,
    title: "索尼降噪耳机",
    imgs: "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ef82c2f354b44e91b70e0fcaa6e321f2~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp",
  },
  {
    no: 9,
    title: "Switch",
    imgs: "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e5b6cc3eaa4b4dbbb8adfe4c43e1c7a3~tplv-k3u1fbpfcp-no-mark:0:0:0:0.awebp?",
  },
]

const app = express();
const cors = require("cors");
// 用于生成jwt字符串的包
const jwt = require("jsonwebtoken");
// 用户将客户端发来的jwt字符串解析成json对象的包
var expressJWT = require("express-jwt");
// 定义secret密钥，建议将密钥命名为secretKey
const secretKey = "gaoxue No1 ^-^";

// // 解决跨域问题
app.use(cors());
// app.all('*', function (req, res, next) {
//   // 设置请求头为允许跨域
//   res.header('Access-Control-Allow-Origin', '*');
//   // 设置服务器支持的所有头信息字段
//   res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, sessionToken');
//   // 设置服务器支持的所有跨域请求的方法
//   res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
//   if (req.method.toLowerCase() == 'options') {
//       res.send(200);  // 让options尝试请求快速结束
//   } else {
//       next();
//   }
// });

// 设置允许接收 json 格式的文件
app.use(express.json());
// 设置允许接收 url 格式的文件
app.use(express.urlencoded({ extended: false }));

// 注册将JWT字符串解析还原成json对象的中间件
// 只要配置成功，就可以吧解析出来的用户信息挂载在req.user属性上

app.use(
  expressJWT.expressjwt({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/api\//],
  })
);
app.use((err, req, res, next) => {
  if (err.name == "UnauthorizedError") {
    return res.send({
      status: 401,
      message: "无效的token",
    });
  }
  res.send({
    status: 500,
    message: "未知的错误",
  });
});

app.listen(8008, () => {
  console.log("服务器启动");
});

// 查询所有数据
app.get("/list", (req, res) => {
  console.log(1111);
  res.send(china);
});
// 分页
app.post("/pages", (req, res) => {
  // query接受出国；来的参数

  let pageIndex = parseInt(req.query.pageIndex);
  let pageNumbers = 0;
  if (req.query.pageNumbers) {
    pageNumbers = parseInt(req.query.pageNumbers);
  } else {
    pageNumbers = 10;
  }

  let page = china.slice(
    (pageIndex - 1) * pageNumbers,
    pageNumbers * pageIndex
  );
  let count = china.length;

  res.send({ count, page });
});
// 删除
app.post("/dellist", (req, res) => {
  let infor = req.body.pid;
  let index = china.findIndex((r) => r.pid == infor);
  china.splice(index, 1);
  res.send(china);
});

// 编辑
app.post("/compile", (req, res) => {
  let pids = req.body.formLabelAlign;

  let index = china.findIndex((r) => r.pid == pids.pid);

  china[index] = JSON.parse(JSON.stringify(pids));
  res.send(true);
});

// 添加
app.post("/addLidst", (req, res) => {
  china.push(req.body.formLabelAlign);
  res.send(true);
});

// 查询包含名称
app.post("/searchList", (req, res) => {
  console.log(req.auth);
  let names = req.body.names;

  let arr = china.filter((r) => r.name.includes(names));

  res.send(arr);
});

// pid查询
app.post("/searchPid", (req, res) => {
  let pids = req.body.pid;
  let arr = china.filter((r) => r.pid == pids);
  console.log(arr);
  res.send(arr);
});

// 注册
app.post("/api/register", (req, res) => {
  let index = users.findIndex((r) => r.login == req.body.registers.login);
  if (index == -1) {
    users.push(req.body.registers);
    res.send({
      msg: "注册成功",
      ststus: 200,
    });
  } else {
    res.send({
      msg: "账户存在",
      ststus: 300,
    });
  }
});

// 登录
app.post("/api/logins", (req, res) => {
  let logins = users.find((r) => r.login == req.body.login);
  if (logins) {
    console.log(logins.Useranme);
    if (req.body.password == logins.Password) {
      tokens = jwt.sign({ username: logins.Useranme }, secretKey, {
        expiresIn: "30h",
      });
      req.tokens = tokens;
      res.send({
        // 参数1：用户得信息对象，参数2：加密的密钥，参数3：配置对象，可以配置当前token有效期
        token: tokens,
        userInfo: logins,
      });
    } else {
      res.send("密码错误");
    }
  } else {
    res.send("账号不存在");
  }
});

// 退出登录
app.post("/api/exit", (req, res) => {});

// 获取线路数据

app.get("/line", (req, res) => {
  res.send(Line);
});

//// 分页
app.post("/pageList", (req, res) => {
  // query接受出国；来的参数

  let pageIndex = parseInt(req.query.pageIndex);
  let pageNumbers = 0;

  if (req.query.pageNumbers) {
    pageNumbers = parseInt(req.query.pageNumbers);
  } else {
    pageNumbers = 10;
  }

  let page = china;
  let count = page.length;

  res.send({ count, page });
});

// 查询包含名称
app.post("/pagsearch", (req, res) => {
  console.log(req.body);
  let names = req.body.names;

  let arr = china.filter((r) => r.name == names);

  res.send(arr);
});




// 获取轮盘数据
app.get('/luckyDraw',(req,res)=>{
  res.send(imgList)
})